package com.hshx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hshx.VO.DeptVo;
import com.hshx.VO.PositionVo;
import com.hshx.pojo.Dept;
import com.hshx.pojo.Job_classification;
import com.hshx.pojo.Position;
import com.hshx.pojo.Users;
import com.hshx.service.IMessageProduceService;
import com.hshx.service.Job_classificationService;
import com.hshx.service.PositionService;
import com.hshx.service.UsersService;
import com.hshx.util.RedisUtil1;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RequestMapping("/systemService")
@RestController
public class PositionController {
    @Autowired
    private PositionService positionService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private Job_classificationService jcs;
    @Autowired
    private RedisUtil1 redisUtil1;
    @Autowired
    private IMessageProduceService service;

    /**
     * 新增一个职位
     * @param position
     * @return
     */
    @RequestMapping("/addPositionOne")
    public boolean addPositionOne(@SpringQueryMap Position position){
        if(jcs.getById(position.getPosition_job()).getJob_classification_state()==2){
            return false;
        }
        if(positionService.save(position)){
            flushPositionAll();
//            this.service.send("direct1","flushPosition","flushPositionAll,");
            return true;
        }
        return false;
    }

    /**
     * 从数据库移除某个职位
     * @param position_id
     * @return
     */
    @RequestMapping("/removePosition")
    public boolean removePosition(int position_id){
        if(usersService.count(new QueryWrapper<Users>().eq("users_position",position_id))>0){
            return false;
        }
        if(positionService.removeById(position_id)){
//            flushPositionAll();
//            flushPositionRedis();
            this.service.send("direct1","flushPosition","flushPositionAll,flushPositionRedis");
            return true;
        }
        return false;
    }

    /**
     * 修改某个职位状态
     * @param position
     * @return
     */
    @RequestMapping("/updatePosition")
    public boolean updatePosition(@SpringQueryMap Position position){
        if(usersService.count(new QueryWrapper<Users>().eq("users_position",position.getPosition_id()))>0
        &&position.getPosition_state()!=1){
            return false;
        }
        if(position.getPosition_job()!=null&&jcs.getById(position.getPosition_job()).getJob_classification_state()==2){
            return false;
        }
        if(positionService.updateById(position)){
//            flushPositionAll();
//            flushPositionRedis();
            this.service.send("direct1","flushPosition","flushPositionAll,flushPositionRedis");
            return true;
        }
        return false;
    }

    /**
     * 查询所有的职位信息
     * @return
     */
    @RequestMapping("/getAllPosition")
    public List<Position> getAllPosition(){
        return positionService.list();
    }

    /**
     * 得到某个职位信息
     * @param position_id
     * @return
     */
    @RequestMapping("/getPosition")
    public Position getPosition(int position_id){
        return positionService.getById(position_id);
    }

    /**
     * 查询所有启用的职位
     * @return
     */
    @RequestMapping("/getPositionList")
    public List<Position> getPositionList(){
        List<Object> objects = redisUtil1.lRange("PositionRedisList", 0, -1);
        if(objects!=null&&objects.size()>0){
            return objects.stream().map(o->((Position)o)).collect(Collectors.toList());
        }
        List<Position> positionList=positionService.list(new QueryWrapper<Position>().eq("position_state",1));
        redisUtil1.lPushAll("PositionRedisList",positionList,24*60l);
        return positionList;
    }

    @RequestMapping("/getPositionPage")
    public Map<String,Object> getPositionPage(Integer page, Integer limit){
        HashMap<String, Object> positionMap = new HashMap<>();
        if(page==null||page<=0){
            page=1;
        }
        if(limit==null||limit<=0){
            limit=10;
        }
        List<Object> objects = redisUtil1.lRange("positionAll",0,-1);
        if(objects!=null&&objects.size()>0){
            System.out.println("redis中存在");

            List<Position> positionList= objects.stream().map(o->((Position)o)).collect(Collectors.toList());
            positionMap.put("code", 0);
            positionMap.put("limit",limit);
            positionMap.put("pages", positionList.size()%limit==0?positionList.size()/limit:positionList.size()/limit+1);
            positionMap.put("pageNum",page);
            positionMap.put("data", positionList.stream().sorted(Comparator.comparing(Position::getPosition_id).reversed()).skip((page-1)*limit).limit(limit).collect(Collectors.toList()));
            positionMap.put("count", positionList.size());
        }else{//redis中不存在或失效
            System.out.println("redis中不存在或失效");

//            Page positionPage= PageHelper.startPage(page,limit);
            List<Position> positionList=positionService.list(new QueryWrapper<Position>().orderByDesc("position_id"));
            redisUtil1.lPushAll("positionAll",positionList,24*60L);
            positionMap.put("code", 0);
            positionMap.put("limit",limit);
//            positionMap.put("pages", page);
//            positionMap.put("pageNum",positionPage.getPageNum());
            positionMap.put("data", positionList.stream().sorted(Comparator.comparing(Position::getPosition_id).reversed()).skip((page-1)*limit).limit(limit).collect(Collectors.toList()));
            positionMap.put("count", positionList.size());
        }
        return positionMap;
    }


    @RequestMapping("/hasPositionName")
    public boolean hasPositionName(String position_name){
        return positionService.count(new QueryWrapper<Position>().eq("position_name",position_name))==0;
    }

    @RequestMapping("/getPositionVoList")
    public List<PositionVo> getPositionVoList(){
        List<Position> positionList = positionService.list(new QueryWrapper<Position>().eq("position_state", 1));
        if(positionList==null||positionList.size()==0){
            return null;
        }
        List<PositionVo> positionVoList = new ArrayList<>();
        positionList.forEach(position -> {
            PositionVo positionVo=new PositionVo();
            positionVo.setPositionName(position.getPosition_name());
            long num=usersService.count(new QueryWrapper<Users>().eq("users_position",position.getPosition_id()));
            positionVo.setPositionNum(num);
            positionVoList.add(positionVo);
        });
        return positionVoList;
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "flushPosition",durable = "true",autoDelete = "true"),
            exchange = @Exchange(value = "direct1",type = ExchangeTypes.DIRECT),
            key = "flushPosition"
    ))
    public void flushPosition(String msg){
        System.out.println("========================flushJobClassRedis====================");
        List<String> stringList = Arrays.asList(msg.split(","));
        for(String str:stringList){
            if("flushPositionAll".equals(str)){
                flushPositionAll();
            }
            if("flushPositionRedis".equals(str)){
                flushPositionRedis();
            }
        }
//        stringList.forEach(e->{
//
//        });

    }

    /**
     * 更新redis中所有的职位
     */
    private void flushPositionAll(){
        redisUtil1.remove("positionAll");
        redisUtil1.lPushAll("positionAll",positionService.list(new QueryWrapper<Position>().orderByDesc("position_id")),24*60L);
    }

    /**
     * 更新redis中所有启用的职位
     */
    private void flushPositionRedis(){
        redisUtil1.remove("PositionRedisList");
        redisUtil1.lPushAll("PositionRedisList",positionService.list(new QueryWrapper<Position>().eq("position_state",1)),60*24L);
    }

}
